package com.milling;

import com.milling.common.utils.scanner.SocketListener;
import com.milling.web.utils.ConfigScanner;
import com.milling.web.utils.SortingScanner;
import com.milling.web.utils.StorageScanner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.net.Socket;

/**
 * 启动程序
 *
 * @author X
 */
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@EnableScheduling
public class CzApplication {

    private static String storageIp = "192.168.237.66";

    private static int storagePort = 2001;

    private static String configIp = "192.168.237.77";

    private static int configPort = 2001;

    //    private static String sortingScannerIp = "192.168.131.66";
    private static String sortingScannerIp = "192.168.237.149";

    private static int sortingScannerPort = 2001;

    private static String host = "192.168.237.178"; // 从配置文件或命令行参数中读取

    private static int port = 502; // 从配置文件或命令行参数中读取

    private static int poolSize = 100; // 从配置文件或命令行参数中读取

    private static int slaveId = 1;
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(CzApplication.class, args);
        //分拣机初始化
//        initSocket();
        //
//        initSocket(context);

        System.out.println("  系统启动成功     ");
    }

/*
    @Configuration
    @ConditionalOnProperty(name = "mac.type", havingValue = "1")
    public class ScannerInitializer {
        @Autowired
        private ConfigurableApplicationContext context;

        @PostConstruct
        public void init() {
            RuoYiApplication.initSocket(context);
        }
    }
*/

    private static void initSocket(ConfigurableApplicationContext context) {
        // 添加重试机制
        int maxRetries = 3; // 最大重试次数
        long retryInterval = 5000; // 重试间隔时间（毫秒）

        // 初始化存储扫码器
        boolean storageConnected = false;
        StorageScanner storageScanner = context.getBean(StorageScanner.class); // 从 Spring 容器获取实例

        for (int i = 0; i < maxRetries && !storageConnected; i++) {
            try {
                Socket socket = new Socket(storageIp, storagePort);
                SocketListener listener = new SocketListener(socket, storageScanner); // 使用 Spring 管理的实例
                new Thread(listener).start();
                storageConnected = true;
                System.out.println("  初始化缓存库入库扫码器完成     ");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("[缓存库入库扫码器]尝试重新连接缓存库入库扫码器... 第 " + (i + 1) + " 次重试");
                try {
                    Thread.sleep(retryInterval);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        }
        if (!storageConnected) {
            System.out.println("存储扫码器连接失败，已达到最大重试次数");
        }

        // 初始化配置扫码器
        boolean configConnected = false;
        ConfigScanner configScanner = context.getBean(ConfigScanner.class); // 从 Spring 容器获取实例

        for (int i = 0; i < maxRetries && !configConnected; i++) {
            try {
                Socket socket2 = new Socket(configIp, configPort);
                SocketListener listener2 = new SocketListener(socket2, configScanner); // 使用 Spring 管理的实例
                new Thread(listener2).start();
                configConnected = true;
                System.out.println("  初始化配针扫码器完成     ");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("[配针扫码器]尝试重新连接配置扫码器... 第 " + (i + 1) + " 次重试");
                try {
                    Thread.sleep(retryInterval);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        }
        if (!configConnected) {
            System.out.println("配针扫码器连接失败，已达到最大重试次数");
        }
    }


    private static void initSocketSorting(ConfigurableApplicationContext context) {
        // 添加重试机制
        int maxRetries = 3; // 最大重试次数
        long retryInterval = 5000; // 重试间隔时间（毫秒）

        // 初始化分拣扫码器

/*
        ObjectPool<ModbusMaster> modbusMasterPool = ModbusMasterPoolFactory.createPool(host, port, poolSize);
        // 创建ModbusService实例
        ModbusTcpService modbusTcpService = new ModbusTcpServiceImpl(modbusMasterPool);

        try {
            String writeResult = modbusTcpService.writeCoilMitsubishi(
                    1,      // 从站ID
                    8192+3,   // 要写入的线圈地址
                    true    // 写入值
            );
            System.out.println("初始化写入结果: " + writeResult);

            Thread.sleep(50);
            boolean[] result = modbusTcpService.readCoilsMitsubishi(
                    1,    // 从站 ID
                    8193,  // 起始地址（例如 M100 对应地址 100）
                    1    // 读取的线圈数量
            );
            System.out.println("初始化读取结果确认: " + result);

            writeResult = modbusTcpService.writeCoilMitsubishi(
                    1,      // 从站ID
                    8192+3,   // 要写入的线圈地址
                    false    // 写入值
            );
            System.out.println("初始化写入结果II: " + writeResult);

            Thread.sleep(50);
            result = modbusTcpService.readCoilsMitsubishi(
                    1,    // 从站 ID
                    8193,  // 起始地址（例如 M100 对应地址 100）
                    1    // 读取的线圈数量
            );
            System.out.println("初始化读取结果确认II: " + result);

        } catch (ModbusTransportException e) {
            System.out.println("Modbus 通信异常: " + e.getMessage());
//            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            modbusMasterPool.close();
        }
*/

        // 初始化分拣机扫码器
        /*boolean sortingConnected = false;
        for (int i = 0; i < maxRetries && !sortingConnected; i++) {
            try {
                Socket socket2 = new Socket(sortingScannerIp, sortingScannerPort);
                SocketListener listener2 = new SocketListener(socket2, new SortingScanner(sortingScannerIp, sortingScannerPort));
                new Thread(listener2).start(); // 启动监听线程
                sortingConnected = true;
                System.out.println("  初始化分拣扫码器完成     ");
            } catch (ConnectException ce) {
                ce.printStackTrace();
                System.out.println("[分拣扫码器]尝试重新连接分拣扫码器... 第 " + (i + 1) + " 次重试");
                try {
                    Thread.sleep(retryInterval);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }catch (SocketException se) {
                se.printStackTrace();
                System.out.println("[配针扫码器]se尝试重新连接存储扫码器... 第 " + (i + 1) + " 次重试");
                try {
                    Thread.sleep(retryInterval);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("[分拣扫码器]ex尝试重新连接分拣扫码器... 第 " + (i + 1) + " 次重试");
                try {
                    Thread.sleep(retryInterval);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        }*/


        boolean sortingConnected = false;
        SortingScanner sortingScanner = context.getBean(SortingScanner.class); // 从 Spring 容器获取实例

        for (int i = 0; i < maxRetries && !sortingConnected; i++) {
            try {
                Socket socket = new Socket(sortingScannerIp, sortingScannerPort);
                SocketListener listener = new SocketListener(socket, sortingScanner); // 使用 Spring 管理的实例
                new Thread(listener).start();
                sortingConnected = true;
                System.out.println("  初始化分拣机扫码器完成     ");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("[分拣机扫码器]尝试重新连接分拣扫码器... 第 " + (i + 1) + " 次重试");
                try {
                    Thread.sleep(retryInterval);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        }
        if (!sortingConnected) {
            System.out.println("分拣扫码器连接失败，已达到最大重试次数");
        }

    }

}
